import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router'
import useMainStore from '@/store/modules/user'
import { initDynamicRouter } from './modules/dynamicRoute'

// 路由白名单
const whiteList: string[] = ['/', '/login', '/404', '/401']

// 静态路由表
const staticRoutes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: () => import('@/views/Login.vue') },
  {
    path: '/:catchAll(.*)',
    hidden: true,
    component: () => import('@/views/404.vue'),
  },
]

const routes: RouteRecordRaw[] = [
  ...staticRoutes,
  {
    name: 'layout',
    path: '/layout',
    meta: {
      title: '首页',
    },
    component: () => import('@/layout/index.vue'),
    redirect: '/layout/home',
    children: [],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach(async (to, from, next) => {
  const { menuList } = useMainStore()
  // 如果跳转路径为白名单就放行
  if (whiteList.includes(to.path)) {
    next()
  }
  // pinia 中的菜单为空就初始化菜单
  else if (!menuList.length) {
    await initDynamicRouter(to, next)
    return
  } else {
    next()
  }
})

export default router
